<template>
	<Modal v-model="modal" :title="modalTitle" @on-visible-change='modalChange'>
		<Form ref="formValidate" :model="editData" :rules="ruleValidate" :label-width="100">
			<FormItem label="账号" prop="userName">
				<Input v-model="editData.userName" placeholder="输入账号"></Input>
			</FormItem>
			<FormItem label="密码" prop="userPwd" v-if="isShowPwd">
				<Input v-model="editData.userPwd" placeholder="输入密码" type="password" />
				<span style="color: #999999;">6-20位字符，可由英文、数字及标点符号组成。</span>
			</FormItem>
			<FormItem label="企业名称" prop="factoryName">
				<Input v-model="editData.factoryName" placeholder="请输入企业名称" />
			</FormItem>
			<FormItem label='联系人' prop='factoryUser'>
				<Input v-model="editData.factoryUser" placeholder="请输入联系人" />
			</FormItem>
			<FormItem label='手机号' prop='factoryTel'>
				<Input v-model="editData.factoryTel" placeholder="请输入手机号" />
			</FormItem>
			
			<FormItem label='经营范围' prop='factoryScope'>
				<Input v-model="editData.factoryScope" type="textarea" />
			</FormItem>
			<FormItem label='状态' prop='isOpen'>
				<Radio-group v-model="editData.isOpen">
					<Radio :label="0">开启</Radio>
					<Radio :label="1">关闭</Radio>
				</Radio-group>
			</FormItem>
			<FormItem label='地址' prop='factoryAddress'>
				<Input v-model="editData.factoryAddress" placeholder="请选择地址" disabled />
			</FormItem>
			<div id="amap">
			
			</div>
		</Form>
		<div slot="footer">
			<Button @click="cancel">取消</Button>
			<Button type="primary" @click="submit" :loading="loadingBtn">
				<span v-if="!loadingBtn">确定</span>
				<span v-else>请稍候...</span>
			</Button>
		</div>
	</Modal>
</template>

<script>
	import uploadImg from '../../components/upload'
	export default {
		components: {
			uploadImg
		},
		props: {
			type: String
		},
		data() {
			//手机号的验证
			const validatePhone = (rule, value, callback) => {
				if (value) {
					if (!/^1[34578]\d{9}$/.test(value)) {
						callback('手机号格式不正确');
					} else {
						callback();
					}
				} else {
					callback();
				}
			};
			//密码的验证
			const validatePwd = (rule, value, callback) => {
				var reg = /^([a-z0-9\.\@\!\#\$\%\^\&\*\(\)]){6,20}$/i;
				if (value) {
					if (!reg.test(value)) {
						callback('密码格式不正确');
					} else {
						callback();
					}
				} else {
					callback();
				}
			};
			//账号重复的验证
			const use = (rule, value, callback) => {
				if(this.partsId!=0){
					
					this.$http.post('/partslog/check/update/name', {
						userName: value,
						partsId:this.partsId
					}).then(res => {
						if (res.status == 200) {
							if (res.data.code == 200) {
								if (res.data.data != 0) {
									callback('账号已存在');
								} else {
									callback();
								}
							}
					
						}
					
					})
					
				}else{
					this.$http.post('/partslog/check/name', {
						userName: value
					}).then(res => {
						if (res.status == 200) {
							if (res.data.code == 200) {
								if (res.data.data != null) {
									callback('账号已存在');
								} else {
									callback();
								}
							}
					
						}
					
					})
				}
				
			};

			return {
				modal: false,
				modalTitle: '',
				editData: {
					factoryName: '',
					factoryUser: '',
					factoryTel: '',
					factoryAddress: '',
					factoryScope: '',
					isOpen: 0,
					userName: '',
					userPwd: '',
					longitude:'',
					latitude:''
				},
				factoryId: 0,
				partsId: 0, //用户id
				isEdit: false,
				ruleValidate: {
					userName: [{
						required: true,
						message: '请输入账号'
					}, {
						validator: use
					}],
					userPwd: [{
						required: true,
						message: '请输入密码'
					}, {
						validator: validatePwd,
						trigger: 'blur'
					}],
					factoryTel: {
						validator: validatePhone,
						trigger: 'blur'
					}
				},
				loadingBtn: false,
				isShowPwd: false
			}
		},
		mounted() {
			this.init()
		},
		methods: {
			 init() {
			  const _this = this;
			  this.map = new AMap.Map("amap");
			  //地图选点
			  var clickHandler = function(e) {
			    if (_this.addressMark) {
			      _this.map.remove(_this.addressMark);
			    }
			    _this.editData.longitude = e.lnglat.lng;
			    _this.editData.latitude = e.lnglat.lat;
			    _this.addressMark = new AMap.Marker({
			      position: e.lnglat, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
			      title: _this.editData.factoryAddress,
			    });
			
			    _this.map.add(_this.addressMark);
			
			    //经纬度转地址
			    AMap.plugin("AMap.Geocoder", function() {
			      var geocoder = new AMap.Geocoder({});
			
			      geocoder.getAddress(e.lnglat, function(status, result) {
			        if (status === "complete" && result.info === "OK") {
			          // result为对应的地理位置详细信息
			          _this.editData.factoryAddress =
			            result.regeocode.formattedAddress;
			        }
			      });
			    });
			  };
			
			  // 绑定事件
			  _this.map.on("click", clickHandler);
			},
			show(res) {


				this.$nextTick(() => {
					this.modal = true
					switch (this.type) {
						case 'add':
							this.isEdit = false
							this.isShowPwd = true
							this.modalTitle = '新增配件商账号'
							break
						case 'edit':
							this.isEdit = true
							this.isShowPwd = false
							this.modalTitle = '编辑配件商账号'
							this.factoryId = res.row.factoryId
							this.partsId = res.row.partsId
							this.$http.post('/partsfactory/queryId', {
								id: res.row.factoryId
							}).then(res => {
								if (res.status == 200) {
									if (res.data.code == 200) {
										this.editData = {
											factoryName: res.data.data.factoryName,
											factoryUser: res.data.data.factoryUser,
											factoryTel: res.data.data.factoryTel,
											factoryAddress: res.data.data.factoryAddress,
											factoryScope: res.data.data.factoryScope,
											isOpen: res.data.data.isOpen,
											userName: res.data.data.userName,
											userPwd: res.data.data.userPwd
										}
									}

								}

							})
							this.modalTitle = '编辑'
							break
					}
				})

			},

			//取消
			cancel() {
				this.modal = false;
				this.partsId = 0;
			},
			//上传成功
			imgUploadSuccess(res) {
				this.editData.userPhoto = res.res.filePath;
			},
			//提交
			submit() {
				this.$refs['formValidate'].validate((valid) => {
					if (valid) {
						let data = {
							factoryName: this.editData.factoryName,
							factoryUser: this.editData.factoryUser,
							factoryTel: this.editData.factoryTel,
							factoryAddress: this.editData.factoryAddress,
							factoryScope: this.editData.factoryScope,
							isOpen: this.editData.isOpen,
							userName: this.editData.userName,
							userPwd: this.editData.userPwd,
							longitude:this.editData.longitude,
							latitude:this.editData.latitude
						}
						let url = '/partsfactory/save'
						if (this.isEdit) {
							data.factoryId = this.factoryId
							data.userPwd = ''
							data.partsId = this.partsId
						}

						this.$http.post(url, data).then(res => {
							if (res.status == 200) {
								if (res.data.code == 200) {
									this.$Message.success('操作成功')
									this.modal = false
									this.$emit('table')
								}

							}
						})
					}

				})

			},
			modalChange(state) {
				if (state) {

				} else {
					this.$refs.formValidate.resetFields()
					this.partsId = 0;
				}
			}
		}
	}
</script>
<style scoped>
	.uploadSuccess {
		width: 200px;
		height: 100px;
	}
	#amap {
	  width: 100%;
	  height: 200px;
	}
</style>
